<!--库存明细-->
<template>
  <div class="inventory-detail-container">
    <!-- 筛选区域 -->
    <div class="controls-section">
        <button class="btn-new" @click="onAdd">新建</button>
        <div class="filters">
            <div class="filter-item">
                <label>关键词</label>
                <input type="text" placeholder="请输入库存编号/产品信息" v-model="query.keyword">
            </div>
            <div class="filter-item">
                <label>产品类型</label>
                <select v-model="query.productType">
                    <option value="">全部</option>
                    <option :value="0">成品</option>
                    <option :value="1">半成品</option>
                    <option :value="2">残次品</option>
                </select>
            </div>
        </div>
        <div class="actions">
            <button class="btn-primary" @click="onSearch">搜索</button>
            <button class="btn-secondary" @click="onReset">重置</button>
        </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="allSelected"></th>
            <th>库存编号</th>
            <th>产品名称</th>
            <th>规格</th>
            <th>分类</th>
            <th>单位</th>
            <th>来源</th>
            <th>所属仓库</th>
            <th>可用库存</th>
            <th>最低库存</th>
            <th>库存单价</th>
            <th>库存金额</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading">
            <td colspan="11" style="text-align: center; padding: 20px;">加载中...</td>
          </tr>
          <tr v-for="(item, index) in inventory" :key="index">
            <td><input type="checkbox" v-model="item.selected"></td>
            <td>{{ item.inventoryNo || '-' }}</td>
            <td class="product-name" @click="viewDetail(item)">{{ item.productName || '-' }} <span class="product-code">{{ item.productCode || '' }}</span></td>
            <td>{{ item.specification || '-' }}</td>
            <td>{{ categoryLabel(item.category) }}</td>
            <td>{{ item.unitName || '-' }}</td>
            <td>{{ item.source || '-' }}</td>
            <td>{{ item.warehouseName || '-' }}</td>
            <td>{{ item.stock ?? '-' }}</td>
            <td>{{ item.minStock ?? '-' }}</td>
            <td>{{ formatPrice(item.purchasePrice) }}</td>
            <td>{{ formatPrice((item.stock || 0) * (item.purchasePrice || 0)) }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="allSelected">
        <label>全选</label>
        <button class="btn-secondary">导出</button>
      </div>
      <div class="pagination">
        <button @click="onPageChange(query.pageNum - 1)" :disabled="query.pageNum === 1">&lt;</button>
        <button v-for="page in totalPages" :key="page" @click="onPageChange(page)" :class="{ active: query.pageNum === page }">{{ page }}</button>
        <button @click="onPageChange(query.pageNum + 1)" :disabled="query.pageNum === totalPages">&gt;</button>
        <select v-model.number="query.pageSize" @change="onPageSizeChange">
          <option value="5">5条/页</option>
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
          <option value="50">50条/页</option>
        </select>
      </div>
    </div>
    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="库存明细详情" width="720px">
      <div class="detail-grid">
        <div class="detail-item">
          <div class="label">库存编号</div>
          <div class="value">{{ detailData.inventoryNo || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">产品名称</div>
          <div class="value">{{ detailData.productName || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">产品编码</div>
          <div class="value">{{ detailData.productCode || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">规格</div>
          <div class="value">{{ detailData.specification || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">分类</div>
          <div class="value">{{ categoryLabel(detailData.category) }}</div>
        </div>
        <div class="detail-item">
          <div class="label">单位</div>
          <div class="value">{{ detailData.unitName || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">来源</div>
          <div class="value">{{ detailData.source || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">所属仓库</div>
          <div class="value">{{ detailData.warehouseName || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">可用库存</div>
          <div class="value">{{ detailData.stock ?? '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">采购单价</div>
          <div class="value">{{ formatPrice(detailData.purchasePrice) }}</div>
        </div>
        <div class="detail-item">
          <div class="label">库存金额</div>
          <div class="value">{{ formatPrice((detailData.stock || 0) * (detailData.purchasePrice || 0)) }}</div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增弹窗 -->
    <el-dialog v-model="addVisible" title="新建库存明细" width="560px">
      <div class="form-grid">
        <div class="form-item">
          <div class="label">库存编号</div>
          <div class="field"><el-input v-model="addForm.inventoryNo" placeholder="系统自动生成" disabled /></div>
        </div>
        <div class="form-item">
          <div class="label">产品名称</div>
          <div class="field">
            <el-select v-model.number="addForm.productId" filterable placeholder="请选择产品" @visible-change="v=>v&&loadProductOptions()" @change="onProductChange">
              <el-option v-for="p in productOptions" :key="p.id" :label="p.name" :value="p.id" />
            </el-select>
          </div>
        </div>
        <div class="form-item">
          <div class="label">规格</div>
          <div class="field">
            <el-select v-model="addForm.specification" filterable placeholder="请选择规格" @visible-change="v=>v&&loadSpecOptions(addForm.productId)">
              <el-option v-for="s in specOptions" :key="s" :label="s" :value="s" />
            </el-select>
          </div>
        </div>
        <div class="form-item">
          <div class="label">分类</div>
          <div class="field">
            <el-select v-model.number="addForm.category" placeholder="请选择">
              <el-option :value="0" label="成品" />
              <el-option :value="1" label="半成品" />
            </el-select>
          </div>
        </div>
        <div class="form-item">
          <div class="label">单位</div>
          <div class="field">
            <el-select v-model.number="addForm.unitId" filterable placeholder="请选择单位" @visible-change="v=>v&&loadUnitOptions()">
              <el-option v-for="u in unitOptions" :key="u.id" :label="u.name" :value="u.id" />
            </el-select>
          </div>
        </div>
        <div class="form-item">
          <div class="label">所属仓库</div>
          <div class="field">
            <el-select v-model.number="addForm.warehouseId" filterable placeholder="请选择仓库" @visible-change="v=>v&&loadWarehouseOptions()">
              <el-option v-for="w in warehouseOptions" :key="w.id" :label="w.name" :value="w.id" />
            </el-select>
          </div>
        </div>
        <div class="form-item">
          <div class="label">来源</div>
          <div class="field">
            <el-select v-model="addForm.source" placeholder="请选择来源">
              <el-option v-for="s in sourceOptions" :key="s.value" :label="s.label" :value="s.value" />
            </el-select>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAdd">提 交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { pageInventoryDetails, getInventoryDetail, addInventoryDetail } from '@/api/warehouse/InventoryDetails'
import { ElMessage } from 'element-plus'
import { listProducts, listUnits, listWarehouses } from '@/api/basic'
export default {
  name: 'InventoryDetail',
  data() {
    return {
      loading: false,
      // 查询条件
      query: {
        keyword: '',
        productType: '',
        pageNum: 1,
        pageSize: 5,
      },
      // 分页数据
      total: 0,
      inventory: [],
      // 详情弹窗
      detailVisible: false,
      detailData: {},
      // 新增弹窗
      addVisible: false,
      addForm: {
        inventoryNo: '',
        productId: undefined,
        specification: '',
        category: 0,
        unitId: undefined,
        warehouseId: undefined,
        source: ''
      },
      productOptions: [],
      unitOptions: [],
      warehouseOptions: [],
      specOptions: [],
      sourceOptions: [
        { label: '自制', value: '自制' },
        { label: '采购', value: '采购' },
        { label: '委外', value: '委外' }
      ]
    };
  },
  computed: {
    allSelected: {
      get() {
        return this.inventory.length > 0 && this.inventory.every(item => item.selected);
      },
      set(value) {
        this.inventory.forEach(item => {
          item.selected = value;
        });
      }
    },
    totalPages() {
      return Math.ceil(this.total / this.query.pageSize);
    }
  },
  created() {
    // 预加载下拉数据用于名称反查
    Promise.all([
      this.loadUnitOptions(),
      this.loadWarehouseOptions()
    ]).finally(() => this.fetchList())
  },
  methods: {
    async fetchList() {
      this.loading = true
      try {
        const payload = {
          // 与后端 InventoryDetailsQueryDTO 对应的字段，按需调整
          productName: (this.query.keyword || '').trim(),
          category: this.query.productType === '' ? undefined : Number(this.query.productType),
          pageNum: this.query.pageNum,
          pageSize: this.query.pageSize,
        }
        const res = await pageInventoryDetails(payload)
        const data = res.data?.data || {}
        const records = data.records || data.list || []
        this.total = data.total || 0
        // 适配选中字段并补全缺失名称/默认值
        const unitMap = new Map(this.unitOptions.map(u => [u.id, u.name]))
        const whMap = new Map(this.warehouseOptions.map(w => [w.id, w.name]))
        this.inventory = records.map(r => ({
          selected: false,
          ...r,
          unitName: r.unitName || (r.unitId != null ? unitMap.get(r.unitId) : r.unitName) || '-',
          warehouseName: r.warehouseName || (r.warehouseId != null ? whMap.get(r.warehouseId) : r.warehouseName) || '-',
          minStock: r.minStock != null ? r.minStock : 0,
          purchasePrice: r.purchasePrice != null ? r.purchasePrice : 0
        }))
      } finally {
        this.loading = false
      }
    },
    onSearch() {
      this.query.pageNum = 1
      this.fetchList()
    },
    onReset() {
      this.query = { keyword: '', productType: '', pageNum: 1, pageSize: 5 }
      this.fetchList()
    },
    onPageChange(page) {
      const totalPages = Math.max(1, Math.ceil(this.total / this.query.pageSize))
      const next = Math.min(Math.max(1, page), totalPages)
      if (next === this.query.pageNum) return
      this.query.pageNum = next
      this.fetchList()
    },
    onPageSizeChange() {
      this.query.pageNum = 1
      this.fetchList()
    },
    async viewDetail(row) {
      if (!row?.id) return
      const res = await getInventoryDetail(row.id)
      this.detailData = res.data?.data || {}
      this.detailVisible = true
    },
    async onAdd() {
      this.resetAddForm()
      this.addVisible = true
    },
    async submitAdd() {
      const { productId, category, unitId, warehouseId, source, inventoryNo, specification } = this.addForm
      if (!productId || !unitId || !warehouseId) {
        ElMessage.error('请填写必填项：产品名称、单位、所属仓库')
        return
      }
      try {
        await addInventoryDetail({ productId, category, unitId, warehouseId, source, inventoryNo, specification })
        ElMessage.success('新增成功')
        this.addVisible = false
        this.fetchList()
      } catch (e) {
        // 错误统一由 http 拦截器提示
      }
    },
    resetAddForm() {
      this.addForm = {
        inventoryNo: '',
        productId: undefined,
        specification: '',
        category: 0,
        unitId: undefined,
        warehouseId: undefined,
        source: ''
      }
    },
    // 加载下拉数据（此处先占位，后续可对接后端列表接口）
    async loadProductOptions() {
      if (this.productOptions.length) return
      try {
        const res = await listProducts({ pageSize: 100 })
        const list = res.data?.data?.records || res.data?.data || res.data || []
        this.productOptions = list.map(x => ({ id: x.id || x.productId, name: x.name || x.productName }))
      } catch (e) {
        // 后端暂无列表接口时，使用库存明细分页作为兜底
        const res2 = await pageInventoryDetails({ pageNum: 1, pageSize: 200 })
        const rec = res2.data?.data?.records || []
        const map = new Map()
        rec.forEach(r => {
          const id = r.productId
          const name = r.productName
          if (id && name && !map.has(id)) map.set(id, name)
        })
        this.productOptions = Array.from(map, ([id, name]) => ({ id, name }))
      }
    },
    async loadUnitOptions() {
      if (this.unitOptions.length) return
      try {
        const res = await listUnits({ pageSize: 100 })
        const list = res.data?.data?.records || res.data?.data || res.data || []
        this.unitOptions = list.map(x => ({ id: x.id || x.unitId, name: x.name || x.unitName }))
      } catch (e) {
        const res2 = await pageInventoryDetails({ pageNum: 1, pageSize: 200 })
        const rec = res2.data?.data?.records || []
        const map = new Map()
        rec.forEach(r => {
          const id = r.unitId
          const name = r.unitName
          if (id && name && !map.has(id)) map.set(id, name)
        })
        this.unitOptions = Array.from(map, ([id, name]) => ({ id, name }))
      }
    },
    async loadWarehouseOptions() {
      if (this.warehouseOptions.length) return
      try {
        const res = await listWarehouses({ pageSize: 100 })
        const list = res.data?.data?.records || res.data?.data || res.data || []
        this.warehouseOptions = list.map(x => ({ id: x.id || x.warehouseId, name: x.name || x.warehouseName }))
      } catch (e) {
        const res2 = await pageInventoryDetails({ pageNum: 1, pageSize: 200 })
        const rec = res2.data?.data?.records || []
        const map = new Map()
        rec.forEach(r => {
          const id = r.warehouseId
          const name = r.warehouseName
          if (id && name && !map.has(id)) map.set(id, name)
        })
        this.warehouseOptions = Array.from(map, ([id, name]) => ({ id, name }))
      }
    },
    async loadSpecOptions(productId) {
      this.specOptions = []
      const params = { pageNum: 1, pageSize: 200 }
      if (productId) params.productId = productId
      const res = await pageInventoryDetails(params)
      const rec = res.data?.data?.records || []
      const set = new Set()
      rec.forEach(r => { if (r.specification) set.add(r.specification) })
      this.specOptions = Array.from(set)
      if (!this.addForm.specification && this.specOptions.length) {
        this.addForm.specification = this.specOptions[0]
      }
    },
    onProductChange(val) {
      this.addForm.specification = ''
      this.loadSpecOptions(val)
    },
    formatPrice(val) {
      const num = Number(val)
      if (Number.isNaN(num)) return '-'
      return num.toFixed(2)
    },
    categoryLabel(val) {
      if (val === 0 || val === '0') return '成品'
      if (val === 1 || val === '1') return '半成品'
      if (val === 2 || val === '2') return '残次品'
      return '-'
    }
  }
}
</script>

<style scoped>
.inventory-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.controls-section {
  display: flex;
  gap: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: center;
}

.btn-new {
    background-color: #409eff;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
}

.filters {
    display: flex;
    gap: 16px;
    align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
}

.filter-item input, .filter-item select {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.filter-item input {
    width: 200px;
}

.actions {
  margin-left: auto;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f8f9fa;
}

.product-name {
    color: #409eff;
    cursor: pointer;
}

.product-code {
  color: #909399;
  font-size: 12px;
  margin-left: 5px;
}

.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination select {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px 24px;
}
.detail-item {
  display: grid;
  grid-template-columns: 96px 1fr;
  align-items: center;
}
.detail-item .label {
  color: #909399;
}
.detail-item .value {
  color: #303133;
  word-break: break-all;
}
.form-grid {
  display: grid;
  grid-template-columns: 1fr;
  row-gap: 12px;
}
.form-item { display: grid; grid-template-columns: 96px 1fr; align-items: center; }
.form-item .label { color: #909399; }
.form-item .field :deep(.el-input),
.form-item .field :deep(.el-select) { width: 100%; }
</style>
